package com.csun.dsms.service.impl;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;
import com.csun.dsms.comment.core.support.BaseService;
import com.csun.dsms.comment.core.utils.wrapper.WrapMapper;
import com.csun.dsms.comment.core.utils.wrapper.Wrapper;
import com.csun.dsms.mapper.JyDataMapper;
import com.csun.dsms.model.education.JyProblemManagement;
import com.csun.dsms.model.education.JyQueryDto;
import com.csun.dsms.service.JyDataService;
import com.csun.dsms.service.JyReminderDataService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class JyDataServiceImpl extends BaseService<JyProblemManagement>
        implements JyDataService {

    @Resource
    private JyDataMapper jyDataMapper;

    @Resource
    private JyReminderDataService jyReminderDataService;

    @Override
    public PageInfo queryListWithPage(JyQueryDto jyQueryDto) {
        PageHelper.startPage(jyQueryDto.getPageNum(),jyQueryDto.getPageSize());
        return new PageInfo<>(jyDataMapper.queryListWithPage(jyQueryDto));
    }


    @Override
    public void downExcelData(HttpServletResponse response) {
        try {
            List<String> row = CollUtil.newArrayList("清单查摆问题表现", "问题大类", "突出问题类型", "整改措施", "责任单位", "牵头领导", "完成时限",
                    "自查自纠发现问题数", "已销号", "整治中", "查处违纪违法案件数", "组织处理人数", "纪律处分人数",
                    "印发通报编号1", "通报涉及本单位问题数1", "印发通报编号2", "通报涉及本单位问题数2", "印发通报编号3", "通报涉及本单位问题数3", "印发通报编号4", "通报涉及本单位问题数4", "印发通报编号5", "通报涉及本单位问题数5",
                    "发出执纪执法建议（文书）数", "建立制度数",
                    "制度名称1", "制度名称2", "制度名称3", "制度名称4", "制度名称5",
                    "是否属于“十大攻坚”","分管领导","其他情况");
            List<List<String>> rows = CollUtil.newArrayList(row,CollUtil.newArrayList());
            ExcelWriter writer = ExcelUtil.getWriter(true);
            writer.write(rows, true);

            //设置宽度20
            for (int i = 0; i < row.size(); i++) {
                writer.setColumnWidth(i, 20);
            }

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
            response.setHeader("Content-Disposition","attachment;filename=ExcelData.xlsx");
            ServletOutputStream out=response.getOutputStream();

            writer.flush(out, true);
            writer.close();
            IoUtil.close(out);
        } catch (Exception e) {
            log.error("导入数据报错", e);
        }
    }

    @Override
    public Wrapper<Object> queryProblemManagementPage(JSONObject reqJson) {
        try {
            Integer pageNum = reqJson.getInteger("pageNum");
            Integer pageSize = reqJson.getInteger("pageSize");
            if (pageNum == null || pageSize == null) {
                return WrapMapper.error("页码和每页数量不能为空");
            }
            PageHelper.startPage(pageNum, pageSize);

            List<JyProblemManagement> problemManagementList = jyDataMapper.queryProblemManagementPage(reqJson);
            PageInfo<JyProblemManagement> pageInfo = new PageInfo<>(problemManagementList);

            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, pageInfo);
        } catch (Exception e) {
            log.error("查询数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> importData(MultipartFile file) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<Map<String, Object>> ExcelList = reader.readAll();
            if (CollectionUtil.isEmpty(ExcelList)) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "Excel不能为空！");
            }
            for (Map<String, Object> excelMap : ExcelList) {
                JyProblemManagement jyProblemManagement = new JyProblemManagement();
                jyProblemManagement.setProminentProblem(Convert.toStr(excelMap.get("清单查摆问题表现")));
                jyProblemManagement.setBigTypeName(Convert.toStr(excelMap.get("问题大类")));
                jyProblemManagement.setProblemType(Convert.toStr(excelMap.get("突出问题类型")));
                jyProblemManagement.setRectificationMeasures(Convert.toStr(excelMap.get("整改措施")));
                jyProblemManagement.setDepartment(Convert.toStr(excelMap.get("责任单位")));
                jyProblemManagement.setResponsibleLeader(Convert.toStr(excelMap.get("牵头领导")));
                jyProblemManagement.setProblemsFoundCount(Convert.toInt(excelMap.get("自查自纠发现问题数")));
                jyProblemManagement.setClosedCount(Convert.toInt(excelMap.get("已销号")));
                jyProblemManagement.setInProgressCount(Convert.toInt(excelMap.get("整治中")));
                jyProblemManagement.setDisciplinaryCases(Convert.toInt(excelMap.get("查处违纪违法案件数")));
                jyProblemManagement.setPunishedPersons(Convert.toInt(excelMap.get("组织处理人数")));
                jyProblemManagement.setDisciplinaryPunishedPersons(Convert.toInt(excelMap.get("纪律处分人数")));
                jyProblemManagement.setRecommendationLetters(Convert.toInt(excelMap.get("发出执纪执法建议（文书）数")));
                jyProblemManagement.setEstablishedSystems(Convert.toInt(excelMap.get("建立制度数")));
                jyProblemManagement.setIsTopTen(Convert.toInt(excelMap.get("是否属于“十大攻坚")));
                jyProblemManagement.setSupervisingLeader(Convert.toStr(excelMap.get("分管领导")));
                jyProblemManagement.setRemark(Convert.toStr(excelMap.get("其他情况")));
                jyProblemManagement.setCreatedTime(DateUtil.date());
                String completionDeadlineStr = Convert.toStr(excelMap.get("完成时限"));
                if (completionDeadlineStr != null && !completionDeadlineStr.isEmpty()) {
                    // 将字符串转换为 Date 对象
                    java.util.Date completionDeadlineDate = DateUtil.parse(completionDeadlineStr);
                    // 格式化日期
                    String formattedDate = DateUtil.format(completionDeadlineDate, "yyyy-MM-dd");
                    jyProblemManagement.setCompletionDeadline(formattedDate);
                }

                List<JSONObject> yftbbhJsonList = CollectionUtil.newArrayList();
                Object yftbbh1 = excelMap.get("印发通报编号1");
                Object tbsjbdwwts1 = excelMap.get("通报涉及本单位问题数1");
                if (yftbbh1 != null && tbsjbdwwts1 != null) {
                    JSONObject yftbbhJson = new JSONObject();
                    yftbbhJson.put("no", Convert.toStr(yftbbh1));
                    yftbbhJson.put("value", Convert.toInt(tbsjbdwwts1));
                    yftbbhJsonList.add(yftbbhJson);
                }
                Object yftbbh2 = excelMap.get("印发通报编号2");
                Object tbsjbdwwts2 = excelMap.get("通报涉及本单位问题数2");
                if (yftbbh2 != null && tbsjbdwwts2 != null) {
                    JSONObject yftbbhJson = new JSONObject();
                    yftbbhJson.put("no", Convert.toStr(yftbbh2));
                    yftbbhJson.put("value", Convert.toInt(tbsjbdwwts2));
                    yftbbhJsonList.add(yftbbhJson);
                }
                Object yftbbh3 = excelMap.get("印发通报编号3");
                Object tbsjbdwwts3 = excelMap.get("通报涉及本单位问题数3");
                if (yftbbh3 != null && !"".equals(tbsjbdwwts3)) {
                    JSONObject yftbbhJson = new JSONObject();
                    yftbbhJson.put("no", Convert.toStr(yftbbh3));
                    yftbbhJson.put("value", Convert.toInt(tbsjbdwwts3));
                    yftbbhJsonList.add(yftbbhJson);
                }
                Object yftbbh4 = excelMap.get("印发通报编号4");
                Object tbsjbdwwts4 = excelMap.get("通报涉及本单位问题数4");
                if (yftbbh4 != null && tbsjbdwwts4 != null) {
                    JSONObject yftbbhJson = new JSONObject();
                    yftbbhJson.put("no", Convert.toStr(yftbbh4));
                    yftbbhJson.put("value", Convert.toInt(tbsjbdwwts4));
                    yftbbhJsonList.add(yftbbhJson);
                }
                Object yftbbh5 = excelMap.get("印发通报编号5");
                Object tbsjbdwwts5 = excelMap.get("通报涉及本单位问题数5");
                if (yftbbh5 != null && tbsjbdwwts5 != null) {
                    JSONObject yftbbhJson = new JSONObject();
                    yftbbhJson.put("no", Convert.toStr(yftbbh5));
                    yftbbhJson.put("value", Convert.toInt(tbsjbdwwts5));
                    yftbbhJsonList.add(yftbbhJson);
                }

                List<JSONObject> zdmcJsonList = CollectionUtil.newArrayList();
                Object zdmc1 = excelMap.get("制度名称1");
                if (zdmc1 != null) {
                    JSONObject zdmcJson = new JSONObject();
                    zdmcJson.put("name", Convert.toStr(zdmc1));
                    zdmcJsonList.add(zdmcJson);
                }
                Object zdmc2 = excelMap.get("制度名称2");
                if (zdmc2 != null) {
                    JSONObject zdmcJson = new JSONObject();
                    zdmcJson.put("name", Convert.toStr(zdmc2));
                    zdmcJsonList.add(zdmcJson);
                }
                Object zdmc3 = excelMap.get("制度名称3");
                if (zdmc3 != null) {
                    JSONObject zdmcJson = new JSONObject();
                    zdmcJson.put("name", Convert.toStr(zdmc3));
                    zdmcJsonList.add(zdmcJson);
                }
                Object zdmc4 = excelMap.get("制度名称4");
                if (zdmc4 != null) {
                    JSONObject zdmcJson = new JSONObject();
                    zdmcJson.put("name", Convert.toStr(zdmc4));
                    zdmcJsonList.add(zdmcJson);
                }
                Object zdmc5 = excelMap.get("制度名称5");
                if (zdmc5 != null) {
                    JSONObject zdmcJson = new JSONObject();
                    zdmcJson.put("name", Convert.toStr(zdmc5));
                    zdmcJsonList.add(zdmcJson);
                }
                jyProblemManagement.setCircularNo(yftbbhJsonList.toString());
                jyProblemManagement.setEstablishedName(zdmcJsonList.toString());
                jyDataMapper.insertSelective(jyProblemManagement);
                jyReminderDataService.addReminder(jyProblemManagement);
            }

            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, "导入数据成功");
        } catch (Exception e) {
            log.error("导入数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }
}
